from __future__ import absolute_import

import logging
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry

from .models import EventData, AlarmData

logger = logging.getLogger(__name__)


@registry.register_document
class EventTraceDocument(Document):

    id = fields.KeywordField()
    event_type = fields.KeywordField()
    event_name = fields.KeywordField()
    event_source = fields.KeywordField()
    resource_type = fields.KeywordField()
    resource_id = fields.TextField()
    resource_name = fields.TextField()
    state = fields.KeywordField()
    level = fields.KeywordField()
    username = fields.KeywordField()
    create_time = fields.DateField()
    details = fields.TextField()

    def prepare_details(self, instance):
        try:
            instance.details["data"]["data_list"] = [*map(dict, instance.details["data"]["data_list"])]
        except Exception as e:
            logger.info("the details %s is dict: %s", instance.event_name, e)
        return str(instance.details)


    class Index:
        name = 'ploto_etest'

        settings = {
            'number_of_shards': 1,
            'number_of_replicas': 1
        }


    class Django:
        model = EventData
        fileds = [
            'id',
            'event_type',
            'event_name',
            'event_source',
            'resource_type',
            'resource_id',
            'resource_name',
            'state',
            'level',
            'username',
            'create_time',
            'details'
        ]


@registry.register_document
class AlarmTraceDocument(Document):

    id = fields.KeywordField()
    alarm_type = fields.KeywordField()
    alarm_name = fields.KeywordField()
    alarm_source = fields.KeywordField()
    state = fields.KeywordField()
    level = fields.KeywordField()
    last_operate_time = fields.DateField()
    details = fields.TextField()

    def prepare_details(self, instance):
        return str(instance.details)

    class Index:
        name = 'ploto_atest'

        settings = {
            'number_of_shards': 1,
            'number_of_replicas': 1
        }

    class Django:
        model = AlarmData
        fileds = [
            'id',
            'alarm_type',
            'alarm_name',
            'alarm_source',
            'state',
            'level',
            'last_operate_time',
            'details'
        ]
